package com.cch.android.activity;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cch.android.activity.view.EdittActivity;
import com.cch.android.activity.view.EffectActivity;
import com.cch.android.activity.view.FrameActivity;
import com.cch.android.activity.view.SetColorActivity;
import com.cch.android.activity.view.VirtualActivity;
import com.cch.android.activity.view.WordEditActivity;
import com.cch.android.imageutil.ImageUtil;
import com.cch.android.util.Constant;
import com.cch.android.util.MyLog;

public class ModelLandscapActivity extends Activity implements OnClickListener{
	
	
	public Context mContext;

	private LinearLayout opeanimagelay,cameraimagelay;
	
	private Button homebtn;
	
	private AlertDialog myDialog;
	
	/**
	 * 剪切图片
	 */
	 private static final int  IMAGE_CUT=2; 
	 
	 /**
	  * 标记是否已经打开图片
	  */
	
	private boolean isOpenIamge = false;
	
	/**
	 * 返回首页
	 */
	private Button homeBtn,saveAndShare;
	
	
	/**
	 * 调节色彩功能，剪切图片,背景虚化，边框，特效，文字
	 */
	private LinearLayout setColorLay,setShearLay,setBgLay,setFrameLay,setEffectLay,setWordLay;
	
	
	/**
	 * 图片view
	 */
	private ImageView imageView;
	/**
	 * 初始化的图片
	 */
	private Bitmap bmpInit;
	/**
	 * 变化后的图片
	 */
	private Bitmap bmpSet;
	
	/**
	 * 图片剪辑参数
	 */
	public static final String IMAGE_UNSPECIFIED = "image/*";
	/**
	 * 图片剪辑结果参数
	 */
	public static final int PHOTORESOULT = 1;
	
	private  String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory()
    + File.separator + "tmpPhoto.jpg";
	
	public static final class HANDLER_KEY{
		public static final int SET_COLOR = 10;			//设置图像色彩
		public static final int initView = 11;			//初始化layout
		public static final int check_apk = 12; 		//检查更新
		public static final int DIALOG_CLOSE = 13; 		//弹出窗关闭
	}
	
	/**
	 * 图片色彩
	 * @author Administrator
	 *
	 */
	public static final class SeekBarDialog{
		public static  int FLAG_SATURATION_PROGRESS = 127;			//饱和度进度条
		public static  int FLAG_LUM_PROGRESS = 127;			//亮度进度条
		public static  int FLAG_HUE_PROGRESS = 127; 		//色相进度条
	}
	/**
	 * 文字风格
	 * @author Administrator
	 *
	 */
	public static final class SeekBarWordDialog{
		public static  int FLAG_SIZE_PROGRESS = 30;			//饱和度进度条
		public static  int FLAG_COLOR_PROGRESS = 30;			//亮度进度条
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.model_setimage_1);
		mContext=this;
		Constant.createSDCardDir(mContext);//创建文件夹
		
		initView();
		Intent intent = getIntent();

		if(bmpInit != null){
			bmpInit.recycle();
			System.gc();
		}
			bmpInit = intent.getParcelableExtra("imageBmp");
		if (bmpInit != null) {
			imageView.setImageBitmap(bmpInit);
		}else{
			changePic();//选择图片
		}
	}
	private void initView(){
		homeBtn = (Button)findViewById(R.id.setimage1_home_btn);
		saveAndShare = (Button)findViewById(R.id.setimage1_save_btn);
		setColorLay = (LinearLayout)findViewById(R.id.setimage1_setcolor_btn);
		setShearLay = (LinearLayout)findViewById(R.id.setimage1_shear_btn);
		setBgLay = (LinearLayout)findViewById(R.id.setimage1_setbg_btn);
		setFrameLay = (LinearLayout)findViewById(R.id.setimage1_frame_btn);
		setEffectLay = (LinearLayout)findViewById(R.id.setimage1_effect_btn);
		setWordLay = (LinearLayout)findViewById(R.id.setimage1_word_btn);
		imageView = (ImageView)findViewById(R.id.setimage1_theimage);
		
		homeBtn.setOnClickListener(this);
		saveAndShare.setOnClickListener(this);
		setColorLay.setOnClickListener(this);
		setShearLay.setOnClickListener(this);
		setBgLay.setOnClickListener(this);
		setFrameLay.setOnClickListener(this);
		setEffectLay.setOnClickListener(this);
		setWordLay.setOnClickListener(this);
		
	}
	private void changePic() {
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.dialog_open, null);
		opeanimagelay = (LinearLayout)layout.findViewById(R.id.openimage);
		cameraimagelay = (LinearLayout)layout.findViewById(R.id.cameraimage);
		opeanimagelay.setOnClickListener(this);
		cameraimagelay.setOnClickListener(this);
		myDialog = new AlertDialog.Builder(mContext).create();
		myDialog.show();
		myDialog.getWindow().setContentView(layout);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.openimage:
			myDialog.dismiss();
			Intent getImage = new Intent(
					Intent.ACTION_GET_CONTENT);
			getImage.addCategory(Intent.CATEGORY_OPENABLE);
			getImage.setType("image/*");
			startActivityForResult(getImage, 0);
			break;
		case R.id.setimage1_save_btn:
			Drawable drawable = imageView.getDrawable();
			if(drawable!=null)
				try {
					String filePath = Constant.saveMyBitmap("cch_"+Constant.fileName, 100, drawable);
					Toast toast = Toast.makeText(getApplicationContext(),
						     getString(R.string.save_image_path)+filePath, Toast.LENGTH_LONG);
						   toast.setGravity(Gravity.CENTER, 0, 0);
						   toast.show();
				} catch (IOException e) {
					e.printStackTrace();
				}
			
			
			break;
       case R.id.cameraimage:
    	   myDialog.dismiss();
//    	   Intent getImageByCamera = new Intent(
//			"android.media.action.IMAGE_CAPTURE");
//	       startActivityForResult(getImageByCamera, 1);
	       
	       
	       Intent takePictureFromCameraIntent = new Intent(
	    		    MediaStore.ACTION_IMAGE_CAPTURE);
	    		  takePictureFromCameraIntent.putExtra(
	    		    android.provider.MediaStore.EXTRA_OUTPUT, Uri
	    		      .fromFile(new File(SD_CARD_TEMP_DIR)));
	    		  startActivityForResult(takePictureFromCameraIntent, 1);
			break;
		case R.id.setimage1_home_btn://返回首页
			if(myDialog!=null)
			 myDialog.dismiss();
			 finish();
			break;
		case R.id.setimage1_setcolor_btn:// 设置图片色彩
			if (bmpInit != null) {
				Intent intentSetColor = new Intent();
				intentSetColor.putExtra("imageBmp", bmpInit);
				intentSetColor.setClass(this, SetColorActivity.class);
				startActivity(intentSetColor);
			}
			break;
		case R.id.setimage1_shear_btn:
			if (bmpInit != null) {
				Intent intentEdit = new Intent();
				intentEdit.putExtra("imageBmp", bmpInit);
				intentEdit.setClass(this, EdittActivity.class);
				startActivity(intentEdit);
			}
			
			break;
		case R.id.setimage1_setbg_btn: //背景虚化
			if (bmpInit != null) {
				Intent intentv = new Intent();
				intentv.putExtra("imageBmp", bmpInit);
				intentv.setClass(this, VirtualActivity.class);
				startActivity(intentv);
			}
			break;
		case R.id.setimage1_frame_btn: //图片边框
			if (bmpInit != null) {
				Intent intentFrame = new Intent();
				intentFrame.putExtra("imageBmp", bmpInit);
				intentFrame.setClass(this, FrameActivity.class);
				startActivity(intentFrame);
			}
			break;
		case R.id.setimage1_word_btn: //图片文字
			if (bmpInit != null) {
				Intent intentWord = new Intent();
				intentWord.putExtra("imageBmp", bmpInit);
				intentWord.setClass(this, WordEditActivity.class);
				startActivity(intentWord);
			}
			break;
		case R.id.setimage1_effect_btn://图片特效
			if (bmpInit != null) {
				Intent intentEffect = new Intent();
				intentEffect.putExtra("imageBmp", bmpInit);
				intentEffect.setClass(this, EffectActivity.class);
				startActivity(intentEffect);
			}
		    break;
		}
		
	}
	@Override
	protected void onDestroy() {
		if (bmpInit != null) {
			bmpInit.recycle();
			System.gc();
			bmpInit=null;
		}
		if (bmpSet != null) {
			bmpSet.recycle();
			System.gc();
			bmpSet=null;
		}
		super.onDestroy();
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			backToHome();
			break;

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
	private void backToHome(){
		finish();
		Intent intent = new Intent();
		intent.setClass(this, ImageMainActivity.class);
		startActivity(intent);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == 0) {
				Uri uri = data.getData();
				if(uri.toString().contains("/"))
				Constant.fileName =uri.toString().substring(uri.toString().lastIndexOf('/')+1, uri.toString().length());
				 MyLog.log("图片名称："+Constant.fileName);
				ContentResolver cr = this.getContentResolver();
				try {
				 MyLog.log("图片名称："+uri.toString());
				


					/*缩放的比例，缩放是很难按准备的比例进行缩放的，其值表明缩放的倍数，SDK中建议其值是2的指数值,值越大会导致图片不清晰*/


//				    byte[] bmpByte = ImageUtil.bitmapToBytes(bmpInit);
				   
				    byte[] bmpByte = ImageUtil.streamToBytes(cr
							.openInputStream(uri));
				    long lenKb = ImageUtil.byteToKb(bmpByte.length);
				    System.out.println("读取图片大小："+lenKb);
				    BitmapFactory.Options opts =ImageUtil.setInSampleSize(lenKb);
					bmpInit = BitmapFactory.decodeStream(cr
							.openInputStream(uri),null,opts);
					
//					/* 将Bitmap设定到ImageView */
				    bmpInit = ImageUtil.scalBitmap(bmpInit,bmpInit.getWidth(),bmpInit.getHeight(),0);
					imageView.setImageBitmap(bmpInit);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			} else if (requestCode == 1) {
				
				ContentResolver resolver = getContentResolver();
				  try {
					 byte[] mContent;
				   File f = new File(SD_CARD_TEMP_DIR);
				   try {
				    Uri capturedImage = Uri
				      .parse(android.provider.MediaStore.Images.Media
				        .insertImage(getContentResolver(), f
				          .getAbsolutePath(), null, null));
				    // Log.i("camera", "Selected image: " +
				    // capturedImage.toString());
				    // f.delete();
				    Toast toast = Toast.makeText(getApplicationContext(),
				      capturedImage.toString(), Toast.LENGTH_SHORT);
				    toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
				    toast.show();
				    //
				    // 将图片内容解析成字节数组
				    mContent = ImageUtil.streamToBytes(resolver.openInputStream(Uri
				      .parse(capturedImage.toString())));
				    // 将字节数组转换为ImageView可调用的Bitmap对象
				    long lenKb = ImageUtil.byteToKb(mContent.length);
				    System.out.println("读取图片大小："+lenKb);
				    BitmapFactory.Options opts =ImageUtil.setInSampleSize(lenKb);
				    bmpInit = BitmapFactory.decodeStream(resolver.openInputStream(Uri
						      .parse(capturedImage.toString())),null,opts);
				    // //把得到的图片绑定在控件上显示
				    bmpInit = ImageUtil.resizeBitmap(bmpInit, Constant.m_screenWidth, Constant.m_screenWidth+100);
				    imageView.setImageBitmap(bmpInit);
				    MyLog.log("拍照返回:"+bmpInit);
				   } catch (FileNotFoundException e) {
				    // TODO Auto-generated catch block
				    e.printStackTrace();
				   }
				  } catch (Exception e) {
					  MyLog.log("拍照返回:"+e);
				   System.out.println(e.getMessage());
				  }
				
			}
			super.onActivityResult(requestCode, resultCode, data);
		}
	}

	//
	public  Bitmap getLoacalBitmap(String url) {
		try {
			FileInputStream fis = new FileInputStream(url);
			return BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}
}
